package com.dwxt.community.exception;

import com.dwxt.common.annotation.*;
import com.dwxt.common.base.*;
import org.slf4j.*;
import org.springframework.validation.*;
import org.springframework.web.bind.*;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @program: intelligentcity
 * @description: 字段验证失败处理
 * @author
 * @create: 2020/04/08
 */
@ControllerAdvice
public class BindExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(BindExceptionHandler.class);

    /**
     * 处理 @Valid 验证失败
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    @ResponseBody
    public BaseResult handleBindException(Exception e) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> list = null;
        if (e instanceof BindException){
            list = ((BindException) e).getFieldErrors();
        }else if (e instanceof MethodArgumentNotValidException){
            list = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
        }

        for (int i=0;i<list.size();i++) {
            FieldError fieldError = list.get(i);
            sb.append(fieldError.getDefaultMessage());
            if (i != list.size()-1){
                sb.append(" | ");
            }
        }
        logger.error(sb.toString());
        return BaseResult.build(StatusCode.PARAMETER_WRONG.getStatus(),sb.toString(),null);
    }
}
